#include "gudb_server.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>

int main(int argc, char* argv[]) {
    // Initialize configuration with defaults
    gudb_server_config_t config;
    gudb_server_init_default_config(&config);
    
    // Parse command line arguments
    int parse_result = gudb_server_parse_args(&config, argc, argv);
    if (parse_result > 0) {
        // Help was shown
        return 0;
    }
    if (parse_result < 0) {
        fprintf(stderr, "Failed to parse arguments\n");
        return 1;
    }
    
    // Create data directory if it doesn't exist
    struct stat st;
    if (stat(config.data_dir, &st) != 0) {
        if (mkdir(config.data_dir, 0755) != 0) {
            fprintf(stderr, "Failed to create data directory: %s\n", config.data_dir);
            return 1;
        }
        printf("Created data directory: %s\n", config.data_dir);
    }
    
    // Validate configuration
    if (config.port <= 0 || config.port > 65535) {
        fprintf(stderr, "Invalid port number: %d\n", config.port);
        return 1;
    }
    
    if (config.max_connections <= 0) {
        fprintf(stderr, "Invalid max connections: %d\n", config.max_connections);
        return 1;
    }
    
    if (config.worker_threads <= 0) {
        fprintf(stderr, "Invalid worker threads: %d\n", config.worker_threads);
        return 1;
    }
    
    // Create and initialize server
    gudb_server_t* server = gudb_server_create();
    if (!server) {
        fprintf(stderr, "Failed to create server\n");
        return 1;
    }
    
    if (gudb_server_init(server, &config) != 0) {
        fprintf(stderr, "Failed to initialize server\n");
        gudb_server_destroy(server);
        return 1;
    }
    
    // Handle daemon mode
    if (config.daemon_mode) {
        printf("Starting GuDB server as daemon...\n");
        pid_t pid = fork();
        
        if (pid < 0) {
            fprintf(stderr, "Failed to fork daemon process\n");
            gudb_server_destroy(server);
            return 1;
        }
        
        if (pid > 0) {
            // Parent process - exit
            printf("GuDB server daemon started with PID %d\n", pid);
            gudb_server_destroy(server);
            return 0;
        }
        
        // Child process - become daemon
        setsid();
        chdir("/");
        freopen("/dev/null", "r", stdin);
        freopen("/dev/null", "w", stdout);
        freopen("/dev/null", "w", stderr);
    }
    
    // Start server
    if (gudb_native_server_start(server) != 0) {
        fprintf(stderr, "Failed to start server\n");
        gudb_server_destroy(server);
        return 1;
    }
    
    // Main server loop
    if (!config.daemon_mode) {
        printf("\nGuDB Server is running. Press Ctrl+C to stop.\n");
        printf("Connection info:\n");
        printf("  Host: %s\n", config.host);
        printf("  Port: %d\n", config.port);
        printf("  Database: %s\n", config.data_dir);
        printf("\nTo connect with GuDB client:\n");
        printf("  gu -h %s -P %d -u %s -i\n\n", config.host, config.port, config.username);
    }
    
    // Wait for shutdown signal
    while (server->running) {
        sleep(1);
        
        // Print stats periodically in verbose mode
        static time_t last_stats = 0;
        if (config.verbose && time(NULL) - last_stats > 60) {
            gudb_server_print_stats(server);
            last_stats = time(NULL);
        }
    }
    
    // Cleanup
    gudb_server_destroy(server);
    
    if (!config.daemon_mode) {
        printf("GuDB server shutdown complete.\n");
    }
    
    return 0;
}